<template>
  <el-table
    ref="tableRef"
    class="w-full"
    :data="data"
    :empty-text="emptyText"
    :row-key="rowKey"
    :tree-props="treeProps"
    :height="height"
    :max-height="maxHeight"
    :lazy="lazy"
    :load="load"
    border
    @select="handleSelect"
    @select-all="handleSelectAll"
    @selectionChange="handleSelectionChange"
    @sortChange="handleSortChange"
    @currentChange="handleCurrentChange"
  >
    <template v-if="$slots.selection">
      <slot name="selection"></slot>
    </template>
    <el-table-column
      v-else-if="selectColumn"
      type="selection"
      :selectable="selectable"
      width="55"
      align="center"
    />
    <slot name="default"></slot>
  </el-table>
</template>
<script setup lang="ts">
import { TableInstance, TreeNode } from 'element-plus'
import { useTemplateRef } from 'vue'

const {
  data = [],
  height,
  maxHeight = 'calc(100vh - 300px)',
  selectable,
  emptyText = '暂无数据',
  lazy,
  load,
  treeProps = {
    hasChildren: 'hasChildren',
    children: 'children',
    checkStrictly: false,
  },
  selectColumn = true,
} = defineProps<{
  data?: Array<any>
  height?: string
  maxHeight?: string
  selectable?: (row: any, index: number) => boolean
  emptyText?: string
  rowKey?: string | ((row: any) => string)
  lazy?: boolean
  load?: (row: any, treeNode: TreeNode, resolve: (data: any[]) => void) => void
  treeProps?: {
    hasChildren?: string
    children?: string
    checkStrictly?: boolean
  }
  selectColumn?: boolean
}>()

const emit = defineEmits([
  'selectionChange',
  'sortChange',
  'currentChange',
  'select',
  'selectAll',
])

const tableRef = useTemplateRef<TableInstance>('tableRef')
defineExpose({ tableRef })

function handleSelectionChange(selection: any[]) {
  emit('selectionChange', selection)
}

function handleSortChange(data: { column: any; prop: string; order: any }) {
  emit('sortChange', data)
}

function handleCurrentChange(currentRow: any, oldCurrentRow: any) {
  emit('currentChange', currentRow, oldCurrentRow)
}

function handleSelect(selection: any[], row: any) {
  emit('select', selection, row)
}

function handleSelectAll(selection: any[]) {
  emit('selectAll', selection)
}
</script>

<style lang="scss" scoped>
.el-table {
  --el-table-header-bg-color: #ebedf1;
  --el-table-border-color: #dddde5;
  --el-table-row-hover-bg-color: #ecf2fe;
  --el-table-text-color: #323843;
  --el-table-header-text-color: #323843;
}
</style>
